09. Limitations of Lambdas

Limitations of Lambdas

ND079 JPND C2 L01 A07 Limitations Of Lambdas

Shortcomings of Lambdas

Lambdas are very useful, but they do have some shortcomings:

  • They can only be used to implement functional interfaces, not classes.
  • Lambdas cannot implement any interface that has multiple abstract methods.
  • Lambdas cannot throw checked exceptions (any subclass of Exception, such as IOException).

Code from the Demo

You can handle checked exceptions with a try-catch inside the lambda:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

public final class ReadFilesMain {
  public static void main(String[] args) throws IOException {
    List<String> fileNames = Arrays.asList("file-a.txt", "file-b.txt", "file-c.txt");

    fileNames.stream()
        .map(Path::of)
        .map(p -> {
          try {
            return Files.readAllLines(p, StandardCharsets.UTF_8)
          } catch (IOException e) {
            return List.of();
          }
        })
        .flatMap(List::stream)
        .forEach(System.out::println);
  }
}

… or with a for loop:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

public final class ReadFilesMain {
    public static void main(String[] args) throws IOException {
        List<String> fileNames = Arrays.asList("file-a.txt", "file-b.txt", "file-c.txt");

        for (String fileName : fileNames) {
            for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
                System.out.println(line);
            }
        }
    }
}